package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.enums.BizCodeEnum;
import net.xdclass.local.ThreadLocal;
import net.xdclass.common.model.LoginUser;
import net.xdclass.common.utils.CommonUtil;
import net.xdclass.common.JsonData;
import net.xdclass.common.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if (StringUtils.isNotEmpty(token)){
            Claims claims = JwtUtil.checkJwt(token);
            if (claims == null){
                CommonUtil.print(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_NEED_LOGIN));
                return false;
            }
            long userId = Long.valueOf(String.valueOf(claims.get("id")));
            String name = (String) claims.get("name");
            String mail = (String) claims.get("mail");
            String headImg = (String) claims.get("headImg");
            LoginUser loginUser = new LoginUser();
            loginUser.setName(name);
            loginUser.setId(userId);
            loginUser.setMail(mail);
            loginUser.setHeadImg(headImg);
            ThreadLocal.setLoginUser(loginUser);
            return true;
        }
        CommonUtil.print(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_NEED_LOGIN));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
